package com.kehutong.api.service;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kehutong.common.Authutil.OAuth2Provider;
import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.oauth2.OAuth2;
import org.coraframework.oauth2.OAuth2Accessor;
import org.coraframework.oauth2.OAuth2ProblemException;
import org.coraframework.oauth2.code.ErrorCode;


import org.coraframework.orm.jdbc.JdbcSession;

@Singleton
public class AccessTokenService {

	static final Logger logger = LoggerFactory.getLogger(AccessTokenService.class);

	@Inject
	private OAuth2Provider oauth2Provider;
	@Inject
	private JdbcSession SignJDBCSession;

	/**
	 * 返回给客户可点用access_token
	 * @param appId
	 * @param secret
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void getAccess_token(String appId, String secret, HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {
		try {
			final OAuth2Accessor accessor = oauth2Provider.getAccessorByAppId(appId);

			if (!accessor.getClient().getSecret().equals(secret)) {
				throw new OAuth2ProblemException(ErrorCode.INVALID_CLIENT);
			}

			oauth2Provider.generateAccessToken(accessor);

			response.setContentType("application/json");
			OutputStream out = response.getOutputStream();

			if (accessor.getRefreshToken() != null) {
				OAuth2.formEncodeInJson(OAuth2.newList(OAuth2.ACCESS_TOKEN, accessor.getAccessToken(),
						OAuth2.EXPIRES_IN, accessor.getExpires_in(), OAuth2.REFRESH_TOKEN, accessor.getRefreshToken()),
						out);
			} else {
				OAuth2.formEncodeInJson(OAuth2.newList(OAuth2.ACCESS_TOKEN, accessor.getAccessToken(),
						OAuth2.EXPIRES_IN, accessor.getExpires_in()), out);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			Boolean sendBodyInJson = true;
			Boolean withAuthHeader = false;
			OAuth2Provider.handleException(e, request, response, sendBodyInJson, withAuthHeader);
		}
	}

//	public JSONResult checkAccessToken(String access_token, CallBack<OAuth2Accessor> call) throws OAuth2ProblemException {
//		OAuth2Accessor accessor = oauth2Provider.getAccessorByAccessToken(access_token);
//		if (Objects.isNull(accessor)) {
//			return Result.error(1003, "授权已失效");
//		}
//
//		call.call(back);
//
//		return Result.success();
//	}
}
